<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Exception;
use think\Request;

class Chat extends Controller
{
    /**
     * 查询聊天敏感词
     * */
    public function getChatSensitive()
    {
        $data = explode(',', str_replace([',', '，'], ',', C('SENSITIVE_WORDS')));

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 聊天用户列表
     * */
    public function chatUserList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('chat_user cu')
            ->field('user_id,to_user_id,new_content,new_content,new_create_time')
            ->where('user_id|to_user_id', $user_id)
            ->order('cu.new_create_time desc')
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['new_create_time'] = formatChatTime($v['new_create_time']);

                $to_user_id = $v['user_id'] == $user_id ? $v['to_user_id'] : $v['user_id'];
                $v['to_user_id'] = $to_user_id;

                $avatar = Db::name('user')->where('id', $to_user_id)->value('avatar');
                $v['avatar'] = doAvatar($avatar);

                $v['username'] = getRealName($to_user_id);

                unset($v['user_id']);

                // 获取未读数据统计数量
                $v['unread_num'] = Db::name('chat_content')->where('user_id', $to_user_id)->where('to_user_id', $user_id)->where('is_read', 0)->count();
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 聊天记录列表
     * */
    public function chatList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $to_user_id = $input['to_user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 20;

        if (empty($user_id) || empty($to_user_id)) apiReturn(1, '暂无数据');

        $list = Db::name('chat_content')
            ->field('id,user_id,to_user_id,content,msg_type,duration')
            ->where(function ($query) use ($user_id, $to_user_id) {
                $query->where('user_id', $user_id)->where('to_user_id', $to_user_id);
            })
            ->whereOr(function ($query) use ($user_id, $to_user_id) {
                $query->where('user_id', $to_user_id)->where('to_user_id', $user_id);
            })
            //            ->page($page, $pagesize)
            ->order('create_time', 'desc')
            ->select();
        if($list){
            foreach($list as &$v){
                $v['duration'] = intval($v['duration'] / 1000) . 's';
                if($v['msg_type'] == 2) $v['url'] = $v['content'];
            }
        }

        Db::name('chat_content')->where('user_id', $to_user_id)->where('to_user_id', $user_id)->where('is_read', 0)->update(['is_read' => 1]);

        apiReturn(1, '获取数据成功', $list ? : []);
    }

    /**
     * 获取未读消息数量
     * */
    public function unreadCount()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $chat_count = Db::name('chat_content')->where('to_user_id', $user_id)->where('is_read', 0)->count();

        $data = [
            'chat_count' => $chat_count,
            'system_count' => 0
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 消息已读
     * */
    public function read()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $to_user_id = $input['to_user_id'];

        if ($user_id && $to_user_id) {
            Db::name('chat_content')->where('user_id', $to_user_id)->where('to_user_id', $user_id)->where('is_read', 0)->update(['is_read' => 1]);
        }
    }

    /**
     * 检测是否可以发消息
     * */
    public function checkCanChat()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $to_user_id = $input['to_user_id'];

        if (!$user_id || !$to_user_id) apiReturn(1, '无权限');

        $user_service_info = Db::name('user_service')->where(['user_id' => $user_id, 'expire_time' => ['gt', time()]])->order('price desc, id desc')->find();
        if (empty($user_service_info) || !$user_service_info['service_id']) apiReturn(1, '无权限');

        $res = getCanChat($user_id, $to_user_id, $user_service_info['service_id']);
        if ($res) {
            apiReturn(1, '有权限');
        } else {
            apiReturn(1, '无权限');
        }
    }

    /**
     * 发送消息
     * */
    public function send()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $to_user_id = $input['to_user_id'];
        $content = $input['content'];

        if ($user_id && $to_user_id && $content) {
            Db::startTrans();
            try {
                $time = time();
                $data = [
                    'user_id' => $user_id,
                    'to_user_id' => $to_user_id,
                    'content' => $content,
                    'create_time' => $time
                ];
                Db::name('chat_content')->insert($data);

                $info = Db::name('chat_user')
                    ->field('date')
                    ->where(function ($query) use ($user_id, $to_user_id) {
                        $query->where('user_id', $user_id)->where('to_user_id', $to_user_id);
                    })
                    ->whereOr(function ($query) use ($user_id, $to_user_id) {
                        $query->where('user_id', $to_user_id)->where('to_user_id', $user_id);
                    })
                    ->find();

                $chat_user_data = [
                    'new_content' => $content,
                    'new_create_time' => $time
                ];
                $date = date('Y-m-d');

                if ($info['date'] != $date) {
                    $chat_user_data['today_user_id'] = $user_id;
                    $chat_user_data['date'] = $date;
                }

                if (empty($info)) {
                    $chat_user_data['user_id'] = $user_id;
                    $chat_user_data['to_user_id'] = $to_user_id;

                    Db::name('chat_user')->insert($chat_user_data);
                } else {
                    Db::name('chat_user')
                        ->where(function ($query) use ($user_id, $to_user_id) {
                            $query->where('user_id', $user_id)->where('to_user_id', $to_user_id);
                        })
                        ->whereOr(function ($query) use ($user_id, $to_user_id) {
                            $query->where('user_id', $to_user_id)->where('to_user_id', $user_id);
                        })
                        ->update($chat_user_data);
                }

                Db::commit();
                apiReturn(1, '发送成功');
            } catch (Exception $e) {
                Db::rollback();
                apiReturn(2, '发送失败');
            }
        } else {
            Db::rollback();
            apiReturn(2, '发送失败');
        }
    }

    /**
     * 上传语音
     * */
    public function uploadVoice()
    {
        if ($_FILES['file']) {
            $dir = './uploads/voice/' . date('Ymd') . '/';
            if (!is_dir($dir)) mkdir($dir, 0777, true);

            $fileName = (time() . '_' . uniqid()) . '_' . basename($_FILES['file']['name']);
            $uploadFile = $dir . $fileName;

            if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
                echo json_encode(['status' => 'success', 'url' => substr($uploadFile, 1)]);
            } else {
                echo json_encode(['status' => 'error', 'message' => '上传失败']);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => '上传失败']);
        }
    }

    /**
     * 发送语音消息
     * */
    public function sendVoice()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $to_user_id = $input['to_user_id'];
        $path = $input['url'];// 语音文件地址
        $duration = $input['duration'];
        $fileSize = $input['fileSize'];

        if ($user_id && $to_user_id && $path) {
            Db::startTrans();
            try {
                $time = time();
                $data = [
                    'user_id' => $user_id,
                    'to_user_id' => $to_user_id,
                    'content' => $path,
                    'duration' => $duration,
                    'file_size' => $fileSize,
                    'msg_type' => 2,
                    'create_time' => $time
                ];
                Db::name('chat_content')->insert($data);

                $info = Db::name('chat_user')
                    ->field('date')
                    ->where(function ($query) use ($user_id, $to_user_id) {
                        $query->where('user_id', $user_id)->where('to_user_id', $to_user_id);
                    })
                    ->whereOr(function ($query) use ($user_id, $to_user_id) {
                        $query->where('user_id', $to_user_id)->where('to_user_id', $user_id);
                    })
                    ->find();

                $chat_user_data = [
                    'new_content' => '[语音消息]',
                    'new_create_time' => $time
                ];
                $date = date('Y-m-d');

                if ($info['date'] != $date) {
                    $chat_user_data['today_user_id'] = $user_id;
                    $chat_user_data['date'] = $date;
                }

                if (empty($info)) {
                    $chat_user_data['user_id'] = $user_id;
                    $chat_user_data['to_user_id'] = $to_user_id;

                    Db::name('chat_user')->insert($chat_user_data);
                } else {
                    Db::name('chat_user')
                        ->where(function ($query) use ($user_id, $to_user_id) {
                            $query->where('user_id', $user_id)->where('to_user_id', $to_user_id);
                        })
                        ->whereOr(function ($query) use ($user_id, $to_user_id) {
                            $query->where('user_id', $to_user_id)->where('to_user_id', $user_id);
                        })
                        ->update($chat_user_data);
                }

                Db::commit();
                apiReturn(1, '发送成功');
            } catch (Exception $e) {
                Db::rollback();
                apiReturn(2, '发送失败');
            }
        } else {
            apiReturn(2, '发送失败');
        }
    }
}
